﻿using DataModel;
using FormatUtil;
using RedisHelp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Timers;

namespace DailyStatistics
{

   
    class Program
    {
        public static RedisHelper redis = new RedisHelper(0);
        static IntPtr _conn = IntPtr.Zero;
        public static System.Timers.Timer aTimer = null;
        public static FixedTimeTask fixedTimeTask = new FixedTimeTask(1, 0);
        static void Main(string[] args)
        {
            DBHelp.DBHelp.Init();
            LogHelp.IniteLog();
            //_conn = TDUtilsTools.TDConnection("36.134.79.195", "root", "Hbbd8991@", "", 0);
            fixedTimeTask.DoWork += FixedTimeTask_DoWork;

            //TDUtilsTools.ExecuteErrorQuery(_conn,"select * ");

            //for (int i =1; i >= 1; i--)
            //{
            FixedTimeTask_DoWork(1);
            //}



            Console.Read();
        }
        private static void FixedTimeTask_DoWork()
        {
            FixedTimeTask_DoWork(0);
        }
        private static void FixedTimeTask_DoWork(double days)
        {
            string date = DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd");
            try
            {
                //CalcReportCheckPointPerson(date);
            }
            catch (Exception ex)
            {
                LogHelp.WriteeLog("", ex.ToString());
            }
            try
            {
                CalcReportCheckPointCar(date);
            }
            catch (Exception ex)
            {

                LogHelp.WriteeLog("", ex.ToString());
            }

        }

        private static void CalcReportCheckPointCar(string date)
        {

            string sqlStr = "SELECT tcw.plan_detail_id,tcw.work_plan_type,tcw.work_plan_id,tcw.work_team_id, tcw.person_id,per.person_name,tcw.effect_date,tcw.device_id ,car.car_id,car.car_num" +
                 ", tcw.start_span,tcw.end_span,fen.check_names,fen.check_points,fen.fence_id" +
                 " FROM  report_check_work as tcw,base_person as per,base_fence as fen ,base_car as car " +
                 "WHERE tcw.person_id = per.person_id and tcw.fence_id = fen.fence_id and tcw.car_id = car.car_id  and tcw.effect_date = '" + date + "' and tcw.work_plan_type = 'car' and tcw.work_state<>0;";

            DataTable devDT1 = DBHelp.DBHelp.QueryDataFromDB(sqlStr);
            if (devDT1 != null && devDT1.Rows.Count > 0)
            {
                for (int i = 0; i < devDT1.Rows.Count; i++)
                {
                    int planDetailId = devDT1.Rows[i]["plan_detail_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["plan_detail_id"].ToString());
                    int work_plan_id = devDT1.Rows[i]["work_plan_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["work_plan_id"].ToString());
                    int work_team_id = devDT1.Rows[i]["work_team_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["work_team_id"].ToString());
                    int deviceId = devDT1.Rows[i]["device_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["device_id"].ToString());
                    string workPlanType = devDT1.Rows[i]["work_plan_type"] == DBNull.Value ? "" : devDT1.Rows[i]["work_plan_type"].ToString();
                    string startSpan = devDT1.Rows[i]["start_span"] == DBNull.Value ? "" : devDT1.Rows[i]["start_span"].ToString();
                    string endSpan = devDT1.Rows[i]["end_span"] == DBNull.Value ? "" : devDT1.Rows[i]["end_span"].ToString();
                    int personId = devDT1.Rows[i]["person_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["person_id"].ToString());
                    string personName = devDT1.Rows[i]["person_name"] == DBNull.Value ? "" : devDT1.Rows[i]["person_name"].ToString();
                    string effectDate = devDT1.Rows[i]["effect_date"] == DBNull.Value ? "" : devDT1.Rows[i]["effect_date"].ToString();
                    string checkNames = devDT1.Rows[i]["check_names"] == DBNull.Value ? "" : devDT1.Rows[i]["check_names"].ToString();
                    string checkPoints = devDT1.Rows[i]["check_points"] == DBNull.Value ? "" : devDT1.Rows[i]["check_points"].ToString();
                    int carId = devDT1.Rows[i]["car_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["car_id"].ToString());
                    string carNum = devDT1.Rows[i]["car_num"] == DBNull.Value ? "" : devDT1.Rows[i]["car_num"].ToString();
                    int fenceId = devDT1.Rows[i]["fence_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["fence_id"].ToString());

                    ReportCheckPoint reportCheckPoint = new ReportCheckPoint();
                    reportCheckPoint.workPlanId = work_plan_id;
                    reportCheckPoint.workTeamId = work_team_id;
                    reportCheckPoint.planDetailId = planDetailId;
                    reportCheckPoint.workPlanType = workPlanType;
                    reportCheckPoint.startSpan = TimeSpan.Parse(startSpan);
                    reportCheckPoint.endSpan = TimeSpan.Parse(endSpan);
                    reportCheckPoint.personId = personId;
                    reportCheckPoint.personName = personName;
                    reportCheckPoint.effectDate = effectDate;
                    reportCheckPoint.checkNames = checkNames;
                    reportCheckPoint.checkPoints = checkPoints;
                    reportCheckPoint.deviceId = deviceId;
                    reportCheckPoint.carId = carId;
                    reportCheckPoint.carNum = carNum;
                    reportCheckPoint.points = QueryFencePoint(fenceId);

                    CalcInCheckPoint(reportCheckPoint);

                }
            }
        }



        /// <summary>
        /// 
        /// </summary>
        private static void CalcReportCheckPointPerson(string date)
        {
            string sqlStr = "SELECT tcw.plan_detail_id,tcw.work_plan_id,work_team_id,tcw.work_plan_type,tcw.person_id,per.person_name,tcw.effect_date,tcw.device_id" +
                 ", tcw.start_span,tcw.end_span,fen.check_names,fen.check_points,fen.fence_id" +
                 " FROM  report_check_work as tcw,base_person as per,base_fence as fen " +
                 " WHERE tcw.person_id = per.person_id and tcw.fence_id = fen.fence_id and tcw.effect_date = '" + date + "' and tcw.work_plan_type = 'person' and tcw.work_state <>0;";

            DataTable devDT1 = DBHelp.DBHelp.QueryDataFromDB(sqlStr);
            if (devDT1 != null && devDT1.Rows.Count > 0)
            {
                for (int i = 0; i < devDT1.Rows.Count; i++)
                {
                    int planDetailId = devDT1.Rows[i]["plan_detail_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["plan_detail_id"].ToString());
                    int work_plan_id = devDT1.Rows[i]["work_plan_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["work_plan_id"].ToString());
                    int work_team_id = devDT1.Rows[i]["work_team_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["work_team_id"].ToString());
                    int deviceId = devDT1.Rows[i]["device_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["device_id"].ToString());
                    string workPlanType = devDT1.Rows[i]["work_plan_type"] == DBNull.Value ? "" : devDT1.Rows[i]["work_plan_type"].ToString();
                    string startSpan = devDT1.Rows[i]["start_span"] == DBNull.Value ? "" : devDT1.Rows[i]["start_span"].ToString();
                    string endSpan = devDT1.Rows[i]["end_span"] == DBNull.Value ? "" : devDT1.Rows[i]["end_span"].ToString();
                    int personId = devDT1.Rows[i]["person_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["person_id"].ToString());
                    string personName = devDT1.Rows[i]["person_name"] == DBNull.Value ? "" : devDT1.Rows[i]["person_name"].ToString();
                    string effectDate = devDT1.Rows[i]["effect_date"] == DBNull.Value ? "" : devDT1.Rows[i]["effect_date"].ToString();
                    string checkNames = devDT1.Rows[i]["check_names"] == DBNull.Value ? "" : devDT1.Rows[i]["check_names"].ToString();
                    string checkPoints = devDT1.Rows[i]["check_points"] == DBNull.Value ? "" : devDT1.Rows[i]["check_points"].ToString();
                    int fenceId = devDT1.Rows[i]["fence_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["fence_id"].ToString());

                    ReportCheckPoint reportCheckPoint = new ReportCheckPoint();
                    reportCheckPoint.workPlanId = work_plan_id;
                    reportCheckPoint.workTeamId = work_team_id;
                    reportCheckPoint.planDetailId = planDetailId;
                    reportCheckPoint.workPlanType = workPlanType;
                    reportCheckPoint.startSpan = TimeSpan.Parse(startSpan);
                    reportCheckPoint.endSpan = TimeSpan.Parse(endSpan);
                    reportCheckPoint.personId = personId;
                    reportCheckPoint.personName = personName;
                    reportCheckPoint.effectDate = effectDate;
                    reportCheckPoint.checkNames = checkNames;
                    reportCheckPoint.checkPoints = checkPoints;
                    reportCheckPoint.deviceId = deviceId;
                    reportCheckPoint.points = QueryFencePoint(fenceId);


                    CalcInCheckPoint(reportCheckPoint);

                }
            }
        }
        private static List<CheckPoint> QueryFencePoint(int fenceId)
        {
            List<CheckPoint> points1 = new List<CheckPoint>();
            string sql = "select point_id,check_name,lat,lng from base_fence_point where fence_id = " + fenceId + "";
            DataTable devDT1 = DBHelp.DBHelp.QueryDataFromDB(sql);
            if (devDT1 != null && devDT1.Rows.Count > 0)
            {
                for (int i = 0; i < devDT1.Rows.Count; i++)
                {
                    string check_name = devDT1.Rows[i]["check_name"] == DBNull.Value ? "" : devDT1.Rows[i]["check_name"].ToString();
                    string lat = devDT1.Rows[i]["lat"] == DBNull.Value ? "" : devDT1.Rows[i]["lat"].ToString();
                    string lng = devDT1.Rows[i]["lng"] == DBNull.Value ? "" : devDT1.Rows[i]["lng"].ToString();
                    int point_id = devDT1.Rows[i]["point_id"] == DBNull.Value ? 0 : int.Parse(devDT1.Rows[i]["point_id"].ToString());

                    var v = new CheckPoint();
                    v.pointId = point_id;
                    v.checkPoint = lat + "," + lng;
                    v.checkName = check_name;
                    v.inOut = false;
                    v.enterTime = new List<string>();
                    points1.Add(v);
                }
            }
            return points1;

        }




        static void CalcInCheckPoint(ReportCheckPoint reportCheckPoint)
        {
            string startDt = reportCheckPoint.effectDate + " " + reportCheckPoint.startSpan + ":00";
            string endDt = reportCheckPoint.effectDate + " " + reportCheckPoint.endSpan + ":00";
            string sqlStr = $"SELECT lat,lng,data_time FROM `dev_gps_history` WHERE device_id={reportCheckPoint.deviceId} and data_time>'{startDt}' and data_time<'{endDt}' ORDER BY data_time asc";
            List<Point> points = new List<Point>();
            DataTable devDT1 = DBHelp.DBHelp.QueryDataFromDB(sqlStr);
            if (devDT1 != null && devDT1.Rows.Count > 0)
            {
                for (int i = 0; i < devDT1.Rows.Count; i++)
                {
                    string lat = devDT1.Rows[i]["lat"] == DBNull.Value ? "" : devDT1.Rows[i]["lat"].ToString();
                    string lng = devDT1.Rows[i]["lng"] == DBNull.Value ? "" : devDT1.Rows[i]["lng"].ToString();
                    string dt = devDT1.Rows[i]["data_time"] == DBNull.Value ? "" : devDT1.Rows[i]["data_time"].ToString();

                    Point point = new Point(lng, lat);
                    point.dateTime = dt;
                    points.Add(point);
                }
            }




            for (int i = 0; i < points.Count - 1; i++)
            {
                reportCheckPoint.mileage += OutInAreaLineAlarm.GetTwoPointsDistance(points[i], points[i + 1]);


                foreach (var item in reportCheckPoint.points)
                {
                    bool isIn = OutInAreaLineAlarm.GetTwoPointsDistance(points[i], new Point(item.checkPoint)) < 10 ? true : false;
                    if (isIn && !item.inOut)
                    {
                        item.inOut = true;
                        //item.enterTime.Add(points[i].dateTime);
                        string sql = $"INSERT INTO  `report_check_point`(`work_plan_id`,work_team_id, `target_type`, `car_id`, `person_id`, `effect_date`, `enter_time`, `create_time`, `mileage`,point_id) VALUES " +
          $"({reportCheckPoint.workPlanId}, {reportCheckPoint.workTeamId},'{reportCheckPoint.workPlanType}', {reportCheckPoint.carId}, {reportCheckPoint.personId},  '{reportCheckPoint.effectDate}', '{points[i].dateTime}', now(), {reportCheckPoint.mileage},{item.pointId});";
                        DBHelp.DBHelp.ExecSql(sql);

                    }
                    if (!isIn && item.inOut)
                    {
                        item.inOut = false;
                    }
                }

            }
            //string enter_count = "";
            //string enter_times = "";
            //foreach (var item in reportCheckPoint.points)
            //{
            //    enter_times += string.Join(',', item.enterTime);
            //    enter_times += "|";
            //    enter_count += item.enterTime.Count;
            //    enter_count += ",";
            //}



            //string sql = $"INSERT INTO  `report_check_point`(`plan_detail_id`, `target_type`, `car_id`, `car_num`, `person_id`, `person_name`, `effect_date`, `check_names`, `check_points`, `enter_count`, `enter_times`, `create_time`, `mileage`) VALUES " +
            //    $"({reportCheckPoint.planDetailId}, '{reportCheckPoint.workPlanType}', {reportCheckPoint.carId}, '{reportCheckPoint.carNum}', {reportCheckPoint.personId}, '{reportCheckPoint.personName}', '{reportCheckPoint.effectDate}', '{reportCheckPoint.checkNames}', '{reportCheckPoint.checkPoints}', '{enter_count.Substring(0, enter_count.Length - 1)}', '{enter_times.Substring(0, enter_times.Length - 1)}', now(), {reportCheckPoint.mileage});";
            //DBHelp.DBHelp.ExecSql(sql);


        }












    }
}
